package xyz.bernkastel.goods_in_great_demand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.bernkastel.goods_in_great_demand.common.CustomException;
import xyz.bernkastel.goods_in_great_demand.entity.Category;
import xyz.bernkastel.goods_in_great_demand.entity.Goods;
import xyz.bernkastel.goods_in_great_demand.entity.Setmeal;
import xyz.bernkastel.goods_in_great_demand.mapper.CategoryMapper;
import xyz.bernkastel.goods_in_great_demand.service.CategoryService;
import xyz.bernkastel.goods_in_great_demand.service.GoodsService;
import xyz.bernkastel.goods_in_great_demand.service.SetmealService;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private GoodsService goodsServer;
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除前需要判断分类有没有商品
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        goodsLambdaQueryWrapper.eq(Goods::getCategoryId, id);
        int count = goodsServer.count(goodsLambdaQueryWrapper);//得到含有该套餐的商品数

        //当前分类包含商品，则抛出业务异常
        if (count > 0) {
            throw new CustomException("当前分类关联了商品，不能删除");

        }

        //当前分类包含套餐，则抛出业务异常
        LambdaQueryWrapper<Setmeal> setMealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        setMealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int count2 = setmealService.count(setMealLambdaQueryWrapper);//得到含有该分类的商品数
        if (count2 > 0) {
            throw new CustomException("当前分类关联了套餐，不能删除");
        }

        //正常删除
        super.removeById(id);
    }
}
